using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using DataLoad.iContact.WinClient.Properties;
using System.Security.Principal;

namespace DataLoad.iContact.WinClient
{
    public partial class frmSettings : Form
    {
        private frmMain _mainForm;

        public frmSettings(frmMain mainForm)
        {
            InitializeComponent();
            _mainForm = mainForm;
        }

        private void btnCredentials_Click(object sender, EventArgs e)
        {
            _mainForm.ShowLogin();
        }

        private void chkWindowsStartup_CheckedChanged(object sender, EventArgs e)
        {
            Settings.Default.StartWithWindows = chkWindowsStartup.Checked;
        }

        private Encryptor _encryptor = new Encryptor(Encryptor.SymmProvEnum.DES);

        private void StoreProxySettings()
        {
            Settings.Default.UseProxy = chkUseProxy.Checked;

            Settings.Default.ProxyURL = edtProxyURL.Text;
            Settings.Default.ProxyUsername = edtProxyUsername.Text;
            Settings.Default.ProxyPort = int.Parse(edtPort.Text);
            if (!string.IsNullOrEmpty(edtProxyPassword.Text))
            {
                Settings.Default.ProxyPassword = _encryptor.Encrypting(edtProxyPassword.Text, Environment.UserName + "GoogleContacts");
            }
            else
            {
                Settings.Default.ProxyPassword = string.Empty;
            }
        }

        private void LoadProxySettings()
        {
            chkUseProxy.Checked = Settings.Default.UseProxy;
            edtProxyURL.Text = Settings.Default.ProxyURL;
            edtProxyUsername.Text = Settings.Default.ProxyUsername;
            edtPort.Text = Settings.Default.ProxyPort.ToString();
            if (!string.IsNullOrEmpty(Settings.Default.ProxyPassword))
            {
                edtProxyPassword.Text = _encryptor.Decrypting(Settings.Default.ProxyPassword, Environment.UserName + "GoogleContacts");
            }
            else
            {
                edtProxyPassword.Text = string.Empty;
            }
        }

        private void btnOK_Click(object sender, EventArgs e)
        {
            StoreProxySettings();

            Settings.Default.Save();

            WindowsIdentity wi = WindowsIdentity.GetCurrent();
            WindowsPrincipal wp = new WindowsPrincipal(wi);

            // From this point onward it is about Windows Startup
            // This checks for local administrator rights if you in a Domain
            if (!wp.IsInRole(WindowsBuiltInRole.Administrator))
            {
                MessageBox.Show("Admin rights required for this operation", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            Cursor.Current = Cursors.WaitCursor;
            try
            {
                // Set windows startup
                AutoStart.Current.EnabledThroughStartupMenu = chkWindowsStartup.Checked;
            }
            catch
            {
                _mainForm.ShowMessage("Unable to change startup settings", "Error", MessageBoxIcon.Error, MessageBoxButtons.OK);
            }
            finally
            {
                Cursor.Current = Cursors.Default;
            }
        }

        public int NameOrderIndex
        {
            get
            {
                if (rbNoChange.Checked)
                {
                    return 0;
                }

                if (rbFirstLast.Checked)
                {
                    return 1;
                }

                if (rbLastFirst.Checked)
                {
                    return 2;
                }

                return 0;
            }

            set
            {
                rbNoChange.Checked = (value == 0);
                rbFirstLast.Checked = (value == 1);
                rbLastFirst.Checked = (value == 2);
            }
        }

        private void frmSettings_Load(object sender, EventArgs e)
        {
            chkWindowsStartup.Checked = Settings.Default.StartWithWindows;
            NameOrderIndex = Settings.Default.NameOrder;
            chkSameColour.Checked = Settings.Default.SameEmailOnly;
            trkFuzzy.Value = Settings.Default.FuzzySearch;
            LoadProxySettings();
        }

        private void trkFuzzy_EditValueChanged(object sender, EventArgs e)
        {
            switch (trkFuzzy.Value)
            {
                case 0:
                    lblLevel.Text = "No Fuzzy Search";
                    break;
                case 1:
                    lblLevel.Text = "Least Fuzzy (less results)";
                    break;
                case 2:
                    lblLevel.Text = "Normal Fuzzy Search (moderate results)";
                    break;
                case 3:
                    lblLevel.Text = "Relaxed Fuzzy Search (more results)";
                    break;
            }

            Settings.Default.FuzzySearch = trkFuzzy.Value;
        }

        private void btnReset_Click(object sender, EventArgs e)
        {
            Settings.Default.MinimiseOnClose = MinimiseOnCloseOptions.Ask.ToString();
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            Settings.Default.Reload();
        }

        private void rgNameOrder_EditValueChanged(object sender, EventArgs e)
        {
            Settings.Default.NameOrder = NameOrderIndex;
        }

        private void chkSameColour_CheckedChanged(object sender, EventArgs e)
        {
            Settings.Default.SameEmailOnly = chkSameColour.Checked;
        }

        private void btnAbout_Click(object sender, EventArgs e)
        {
            using (frmAbout frm = new frmAbout())
            {
                frm.ShowDialog();
            }
        }

        private void chkUseProxy_CheckedChanged(object sender, EventArgs e)
        {
            foreach (Control ctrl in grpProxy.Controls)
            {
                if (ctrl.Name != chkUseProxy.Name)
                {
                    ctrl.Enabled = chkUseProxy.Checked;
                }
            }
        }

        private void edtPort_KeyPress(object sender, KeyPressEventArgs e)
        {
            e.Handled = (!Char.IsNumber(e.KeyChar) && (!Char.IsControl(e.KeyChar)));
        }

        private void DeleteContacts(List<DLContact> list)
        {
            foreach (DLContact contact in list)
            {
                contact.Contact.Delete();
            }
        }

        private void btnEmpty_Click(object sender, EventArgs e)
        {
            List<DLContact> found = _mainForm.AllContacts.FindAll(delegate(DLContact match)
            {
                if (match.Contact != null)
                {
                    return ((match.Contact.Emails.Count == 0) &&
                            (match.Contact.PostalAddresses.Count == 0) &&
                            (match.Contact.Organizations.Count == 0) &&
                            (match.Contact.IMs.Count == 0) &&
                            (match.Contact.Phonenumbers.Count == 0) &&
                            (!match.HasNotes));
                }
                else
                {
                    return false;
                }
            });

            using (frmContactSummary frm = new frmContactSummary())
            {
                if (frm.Show(found) == DialogResult.OK)
                {
                    if (MessageBox.Show("Are you sure?", "Please confirm", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                    {
                        DeleteContacts(found);
                    }
                }
            }
        }

        private void btnDuplicates_Click(object sender, EventArgs e)
        {
            List<DLContact> all = new List<DLContact>(_mainForm.AllContacts);
            List<DLContact> found = new List<DLContact>();

            foreach (DLContact contact in all)
            {
                if (contact.Contact != null)
                {
                    // Names similar?
                    foreach (DLContact c in all)
                    {
                        if ((c != contact) && (c.IsDuplicate(contact)))
                        {
                            found.Add(contact);
                        }
                    }
                }
            }

            using (frmContactSummary frm = new frmContactSummary())
            {
                if (frm.Show(found) == DialogResult.OK)
                {
                    if (MessageBox.Show("The selected contacts will be merged. No data will be lost", "Please confirm", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                    {
                        MergeContacts(found);
                    }
                }
            }
        }

        private void MergeContacts(List<DLContact> found)
        {
            throw new NotImplementedException();
        }
    }
}